from flask import request, g
from flask_login import current_user
from app.models import Log
from functools import wraps
import time


def log_request(f):
    """请求日志装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        start_time = time.time()
        
        # 执行原始函数
        response = f(*args, **kwargs)
        
        # 计算请求处理时间
        processing_time = time.time() - start_time
        
        # 记录请求日志
        try:
            # 获取请求信息
            ip_address = request.remote_addr
            user_agent = request.headers.get('User-Agent', '')
            url = request.url
            method = request.method
            
            # 获取响应状态码
            status_code = getattr(response, 'status_code', 200)
            
            # 确定日志级别
            if status_code >= 500:
                level = 'ERROR'
                message = f'{method} {url} - 服务器错误 ({status_code})'
            elif status_code >= 400:
                level = 'WARNING'
                message = f'{method} {url} - 客户端错误 ({status_code})'
            else:
                level = 'INFO'
                message = f'{method} {url} - 成功 ({status_code})'
            
            # 记录详细信息
            details = f'处理时间: {processing_time:.4f}秒\n'
            details += f'请求方法: {method}\n'
            details += f'请求路径: {request.path}\n'
            details += f'查询参数: {dict(request.args)}\n'
            
            # 只对非敏感请求记录表单数据
            if request.form and not any(sensitive in request.path.lower() 
                                        for sensitive in ['login', 'password', 'token']):
                details += f'表单数据: {dict(request.form)}\n'
            
            # 记录日志
            Log.log(
                level=level,
                message=message,
                details=details,
                ip_address=ip_address,
                user_agent=user_agent,
                url=url,
                user_id=current_user.id if current_user.is_authenticated else None
            )
        except Exception as e:
            # 记录日志失败不应该影响正常请求
            print(f"记录请求日志失败: {str(e)}")
        
        return response
    
    return decorated_function


def log_user_action(action, details=None):
    """记录用户操作"""
    try:
        ip_address = request.remote_addr
        user_agent = request.headers.get('User-Agent', '')
        url = request.url
        
        Log.info(
            message=f'用户操作: {action}',
            details=details,
            ip_address=ip_address,
            user_agent=user_agent,
            url=url,
            user_id=current_user.id if current_user.is_authenticated else None
        )
    except Exception as e:
        print(f"记录用户操作失败: {str(e)}")


def log_system_event(level, message, details=None):
    """记录系统事件"""
    try:
        ip_address = request.remote_addr if request else None
        user_agent = request.headers.get('User-Agent', '') if request else ''
        url = request.url if request else None
        
        Log.log(
            level=level,
            message=message,
            details=details,
            ip_address=ip_address,
            user_agent=user_agent,
            url=url,
            user_id=current_user.id if current_user.is_authenticated else None
        )
    except Exception as e:
        print(f"记录系统事件失败: {str(e)}")